package com.example.dell.basic;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.dell.basicapplication.R;
import com.example.dell.utils.ThreadUtil;
import com.example.dell.weigit.LoadingView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

public abstract class BasicFragment extends Fragment {

    private View                      mContentView;
    private RelativeLayout            mFleft;
    private TextView                  mFtitletext;
    private RelativeLayout            mFright;
    private FrameLayout               mFcontentLayout;
    private LinearLayout              mFmBasicBar;
    private View                      mFNormalView;
    private View                      mFWaitView;
    private View                      mFNoNetView;
    private SmartRefreshLayout        mFRefrsh;
    private View                      mFNoDataView;
    private SmartRefreshLayout        mFNoRefrsh;
    private LinearLayout.LayoutParams mLayoutParams;
    private LoadingView               mDialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.activity_basic_basic, container, false);

        mFleft = (RelativeLayout) mContentView.findViewById(R.id.left);
        mFtitletext = (TextView) mContentView.findViewById(R.id.titletext);
        mFright = (RelativeLayout) mContentView.findViewById(R.id.right);
        mFcontentLayout = (FrameLayout) mContentView.findViewById(R.id.content_layout);
        mFmBasicBar = (LinearLayout) mContentView.findViewById(R.id.basic_actionbar);


        //加载正常界面前的等待状态
        mFWaitView = inflater.inflate(R.layout.wait_layout, null);

        //无网界面
        mFNoNetView = inflater.inflate(R.layout.nonet_layout, null);

        //无数据状态
        mFNoDataView = inflater.inflate(R.layout.page_error, null);

        //正常界面
        mFNormalView = inflater.inflate(setLayoutResourceID(), null);
        initView(mFNormalView);


        mFRefrsh = (SmartRefreshLayout) mFNoNetView.findViewById(R.id.refreshLayout);
        mFRefrsh.setEnableLoadMore(false);
        mFRefrsh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mFRefrsh.finishRefresh(0);
                mCurrentState = DTAESTATE.LOADING;
                changeView();

                initData();
            }
        });



        mFNoRefrsh = (SmartRefreshLayout) mFNoDataView.findViewById(R.id.uichengerefrash);
        mFNoRefrsh.setEnableLoadMore(false);
        mFNoRefrsh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mFNoRefrsh.finishRefresh(0);
                //页面切换的方法
                mCurrentState = DTAESTATE.LOADING;
                changeView();
                initData();

            }
        });
        mFNoDataView.findViewById(R.id.btn_reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //页面切换的方法
                mCurrentState = DTAESTATE.LOADING;
                changeView();
                initData();
            }
        });

        mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);


        //将四个布局添加在一起
        //加载成功的界面
        mFcontentLayout.addView(mFNormalView, mLayoutParams);
        //加载中的界面
        mFcontentLayout.addView(mFWaitView, mLayoutParams);
        //无数据界面
        mFcontentLayout.addView(mFNoDataView, mLayoutParams);
        //无网界面
        mFcontentLayout.addView(mFNoNetView, mLayoutParams);


        //页面切换的方法
        changeView();

        initData();

        return mContentView;
    }


    //定义三个状态
    private enum DTAESTATE {
        LOADING,//正在加载中
        SUCCESS,//加载成功
        ERROR,//加载失败
        NONET,;//无网界面

    }

    //定义一个当前状态（默认正在加载中）
    private DTAESTATE mCurrentState = DTAESTATE.LOADING;

    private void changeView() {
        //先将三个页面都隐藏
        mFWaitView.setVisibility(View.GONE);
        mFNoDataView.setVisibility(View.GONE);
        mFNoNetView.setVisibility(View.GONE);
        mFNormalView.setVisibility(View.GONE);
        hideProgree();
        //根据当前状态切换
        switch (mCurrentState) {
            case LOADING:
                showLoading();
                mFWaitView.setVisibility(View.VISIBLE);
                break;
            case SUCCESS:
                mFNormalView.setVisibility(View.VISIBLE);
                break;
            case ERROR:
                mFNoDataView.setVisibility(View.VISIBLE);
                break;
            case NONET:
                mFNoNetView.setVisibility(View.VISIBLE);
                break;
        }

    }

    protected void showLoading() {
        if (getContext() == null) {
            return;
        }
        if (mDialog == null) {
            mDialog = new LoadingView(getContext(), R.style.CustomDialog);
        }
        if (mDialog.getOwnerActivity() == null) {
            hideProgree();
            return;
        } else {
            mDialog.show();
        }

    }

    //隐藏加载进度圈
    protected void hideProgree() {
        if (mDialog != null) {
            mDialog.dismiss();
        }

    }

    /**
     * 自动切换Ui，网络请求完，需要调用该方法来切换Ui,再initData中使用，网络请求完成数据后，
     *
     * @param haveNet 当前是否有网无网传 false ，有网的时候传true
     * @param obj     ，请求失败后传null ，如果有数据就传一个部位空的对象
     */
    protected void autoShowPager(boolean haveNet, final Object obj) {
        //如果是无网状态
        if (!haveNet) {
            mCurrentState = DTAESTATE.NONET;
            changeView();
            return;
        } else {
            //如果是有网状态,子线程获取数据
            //获取网络数据
            mCurrentState = checkData(obj);
            //主线程切换Ui
            changeView();
        }
    }

    private DTAESTATE checkData(Object obj) {
        if (!isConnected()) {
            return DTAESTATE.NONET;
        } else {
            if (obj == null) {//如果数据为空，则失败
                return DTAESTATE.ERROR;
            } else {
                if (obj instanceof List) {//如果返回的是数组
                    List list = (List) obj;
                    if (list.size() > 0) {
                        return DTAESTATE.SUCCESS;
                    } else {
                        return DTAESTATE.ERROR;
                    }
                } else {//如果是对象
                    return DTAESTATE.SUCCESS;
                }
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    /**
     * @return 初始化View
     */
    protected abstract int setLayoutResourceID();

    /**
     * @param view 初始化view
     */
    protected abstract void initView(View view);

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 判断是否有网络
     */
    protected boolean isConnected() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    /**
     * @param tag
     * @param resID 点击左面的返回按钮
     */
    protected void setLeftShow(int tag, int resID) {
        if (null == mFleft) {
            mFleft = (RelativeLayout) mContentView.findViewById(R.id.left);
        }
        mFleft.removeAllViews();
        mFleft.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mFleft.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mFleft.addView(view, params);
        } else if (tag == 3) {
            View view = getLayoutInflater().inflate(R.layout.weightback, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mFleft.addView(view, params);
        }
    }

    /**
     * @param title 设置标题
     */
    protected void setTitleText(String title) {

        if (mFtitletext == null) {
            mFtitletext = (TextView) mContentView.findViewById(R.id.titletext);
        }
        mFtitletext.setText(title);
    }

    /**
     * 设置右边边按钮里是文字 setRightShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    protected void setRightShow(int tag, int resID) {
        if (null == mFright) {
            mFright = (RelativeLayout) mContentView.findViewById(R.id.right);
        }
        mFright.removeAllViews();
        mFright.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mFright.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mFright.addView(view, params);
        }
    }

    public RelativeLayout getLeft() {
        return mFleft;
    }

    public TextView getTitletext() {
        return mFtitletext;
    }

    public RelativeLayout getRight() {
        return mFright;
    }

    public LinearLayout getBasicBar() {
        return mFmBasicBar;
    }

    public void setBasicBar(LinearLayout basicBar) {
        mFmBasicBar = basicBar;
    }
}
